/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.share.factory;

import android.app.Activity;

import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class OpenBuilder {
    private Activity activity;

    public static OpenBuilder with(Activity activity) {
        OpenBuilder builder = new OpenBuilder();
        builder.activity = activity;
        return builder;
    }

    public WechatOperator useWechat(String appId) {
        return new WechatOperator(appId);
    }

    public class WechatOperator {
        String appId;

        WechatOperator(String appId) {
            this.appId = appId;
        }

        public void login(Callback callback) {
            IWXAPI iwxapi = init();
            if (iwxapi == null) {
                if (callback != null)
                    callback.onFailed();
                return;
            }
            // 唤起微信登录授权
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_login";
            // 失败回调
            if (!iwxapi.sendReq(req) && callback != null) {
                callback.onFailed();
            } else {
                if (callback != null)
                    callback.onSuccess();
            }
        }

        private IWXAPI init() {
            IWXAPI iwxapi = WXAPIFactory.createWXAPI(activity, appId, false);
            if (iwxapi.isWXAppInstalled() && iwxapi.getWXAppSupportAPI()>= Build.TIMELINE_SUPPORTED_SDK_INT && iwxapi.registerApp(appId)) {
                return iwxapi;
            }
            return null;
        }
    }

    public interface Callback {
        void onFailed();

        void onSuccess();
    }
}
